﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OBUCare.Core.Models;
using OBUCare.Core.DataAccess;
using Telerik.Web.Mvc;
using OBUCare.Web.Models;
using OBUCare.Web.Infrastructure;
using OBUCare.Core.BL;
using OBUCare.Core.Common;

namespace OBUCare.Web.Controllers
{
    /// <summary>
    /// 发票相关
    /// </summary>
    public class InvoiceController : Controller
    {
        private OBU_CAREContext db = new OBU_CAREContext();
        OBUCareOrderMgr obuMgr = new OBUCareOrderMgr();
        UserMgr uMgr = new UserMgr();
        ConfigMgr configMgr = new ConfigMgr();



        public ActionResult Index(string IDs)
        {
            ViewBag.IDs = IDs;
            return View();
        }

        /// <summary>
        /// 用于ajax访问，并返回数据的Action
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [GridAction]
        public ActionResult List(string IDs, string searchSql, string AgentNo)
        {
            //交流流水信息
            IEnumerable<PRINT_LOGINVOICE> transactions = null;

            //var allItems = db.PRINT_LOG;
            var allItems = GetInvoice(searchSql, AgentNo);
            if (IDs.IsNullOrEmpty())
                transactions = allItems;
            else
            {
                var idArray = IDs.Split(',').Distinct();

                var longIDs = from id in idArray
                              select id.ToLong().Value;

                transactions = from i in allItems
                               where longIDs.Contains(i.ID)
                               select i;
            }
            var model = (from t in transactions
                         select toTransactionLogViewModel(t)).OrderByDescending(t => t.CREATED_DATE).ToList();


            var temp = new GridModel(model);
            return View(temp);
        }

        private TransactionLogViewModel toTransactionLogViewModel(PRINT_LOGINVOICE log)
        {
            TransactionLogViewModel m = new TransactionLogViewModel();
            m.CREATED_DATE = log.CREATED_DATE;
            m.ID = log.ID;
            m.TransactionLogID = null;
            m.TransactionTypeID = log.OPERATION_KIND.ToText();
            m.TransactionType = configMgr.GetTypeValue(ConfigMgr.tblTransactionType, log.OPERATION_KIND.ToText()).DICT_TITLE;

            //var baseInfo = obuMgr.GetObuInfo(log.);
            //if (baseInfo != null)
            //{
            //    m.User_name = baseInfo.USER_NAME;
            //    m.USER_NO = baseInfo.USER_NO;
            //}

            m.SERIAL_NO = null;
            m.SERIAL_ID = null;


            m.ReturnPrice = 0; //todo:处理金额
            m.RepairPrice = log.AMOUNT;
            m.OtherPrice = 0;
            m.ServicePrice = 0;
            m.REMARK = log.REMARK;


            m.SumPrice = m.ReturnPrice + m.RepairPrice + m.OtherPrice + m.ServicePrice;
            m.Agent = log.AGENT_NO;
            m.AgentName = log.AGENT_NAME;
            m.Operator = log.OPERATOR_NO;
            m.OperatorName = log.OPERATOR_NAME;
            m.SERIAL_NO = log.SERIAL_NO;
            m.OPERATION_KIND = log.OPERATION_KIND;

            return m;
        }


        public IEnumerable<PRINT_LOGINVOICE> GetInvoice(string sqlWhere, string AgentNo)
        {
            if (AgentNo != null && AgentNo != "")
                AgentNo = " AND P.AGENT_NO='" + AgentNo + "' ";
            //如果查询条件为空 则显示当前营业厅的所有的信息 如果是维修组 可查看所有
            if (sqlWhere.Trim() == "")
                sqlWhere = " AND INVOICE.ID IS NULL AND p.[CREATED_DATE]>'" + DateTime.Now.ToShortDateString() + "' AND p.[CREATED_DATE]<'" + DateTime.Now.AddDays(1).ToShortDateString() + "' " + AgentNo;
               // [OLD] sqlWhere = " AND (INVOICE.ID IS NULL OR INVO.STATUS=0) AND p.[CREATED_DATE]>'" + DateTime.Now.ToShortDateString() + "' AND p.[CREATED_DATE]<'" + DateTime.Now.AddDays(1).ToShortDateString() + "' " + AgentNo;
            else
                sqlWhere = sqlWhere + " AND INVOICE.STATUS IS NULL ";
            // 132行： 原来是// LEFT JOIN INVOICE_DETAIL AS INVOICE ON P.ID=INVOICE.SERIAL_ID 
            // LEFT JOIN INVOICE_INFO AS INVO ON INVOICE.INVOICE_ID=INVO.ID
            //现在改成  left join ( select A.SERIAL_ID,B.ID,B.STATUS from INVOICE_DETAIL AS A INNER JOIN INVOICE_INFO AS B ON A.INVOICE_ID=B.ID and b.status=1) AS INVOICE ON P.ID=INVOICE.SERIAL_ID  
            string sqlStr = @"SELECT DISTINCT p.[ID]
                                  ,p.[SERIAL_NO]
                                  ,p.OPERATOR_NO,E.OPERATOR_NAME
                                  ,p.AGENT_NO,AGENT.AGENT_NAME
                                  ,p.[CREATED_DATE]
                                  ,p.USER_NO
                                  ,p.CLIENT_IP
                                  ,p.REMARK
                                  ,ol.OPERATION_KIND
                                  ,ol.AMOUNT,ol.ID 
                              FROM [PRINT_LOG] p inner join PRINT_DETAIL d on d.SERIAL_ID =p.ID
 inner join dbo.OPERATION_CARE_LOGS ol on ol.ID = d.Log_ID AND ol.STATUS=1
 left join ( select A.SERIAL_ID,B.ID,B.STATUS from INVOICE_DETAIL AS A INNER JOIN INVOICE_INFO AS B ON A.INVOICE_ID=B.ID and b.status=1) AS INVOICE ON P.ID=INVOICE.SERIAL_ID  
 LEFT JOIN (SELECT AGENT_NO,AGENT_NAME,AGENT_TYPE_NO FROM ISSUE_RPT.DBO.ISSUER_AGENTS
 UNION ALL 
 SELECT ISSUER_NO AGENT_NO,ISSUER_NAME AGENT_NAME,'' AGENT_TYPE_NO FROM ISSUE_RPT.DBO.ISSUERS)
 AS AGENT ON AGENT.AGENT_NO=P.AGENT_NO
 LEFT JOIN (SELECT * FROM ISSUE_RPT.DBO.OPERATORS) AS E ON P.OPERATOR_NO=E.OPERATOR_NO

 WHERE p.STATUS=1  AND OL.AMOUNT>0  AND OL.OPERATION_KIND!=" + TransactionType.ReturnDeposit.ToInt() + sqlWhere;//INVOICE.ID IS NULL 

            return db.Database.SqlQuery<PRINT_LOGINVOICE>(sqlStr);
        }
        [HttpPost]
        public ActionResult InsertConfirmed()
        {
            //如果以参数的形式传过来，则只能取到最后一个值
            string checkedRecords = Request.Form["checkedRecords"];
            if (checkedRecords != null)
            {
                IList<long> logIds = checkedRecords.Split(',').ConvertTo(i => i.ToLong().Value).Distinct().ToList();

                PRINT_LOG log = null;
                if (logIds.Count > 0)
                {
                    log = obuMgr.GetPrintLogs(logIds[0]);
                    var u = UIUtility.GetCurrentUser();
                    var Invoices = getInvoiceInfos(log, u);

                    obuMgr.NewInvoice(logIds, log.USER_NO, u, Invoices);
                }
            }
            return Content("<Script>alert('信息提交成功！');window.location.href='/Invoice/Index'; </Script>");
            //return RedirectToAction("Index");
        }

        /// <summary>
        /// 从From中获取发票的相关信息
        /// </summary>
        /// <param name="log"></param>
        /// <param name="u"></param>
        /// <returns></returns>
        private IList<INVOICE_INFO> getInvoiceInfos(PRINT_LOG log, OPERATOR u)
        {
            List<INVOICE_INFO> list = new List<INVOICE_INFO>();

            for (int i = UIConstants.InvoiceControlFromIndex; i <= UIConstants.InvoiceControlToIndex; i++)
            {

                var form = Request.Form;
                decimal? amount = form["AMOUNT" + i.ToString()].Todecimal();
                string invoiceNo = form["INVOICE_NO" + i.ToString()].ToString();
                if (amount.HasValue && invoiceNo != "" && invoiceNo.Length > 0 && amount > 0)
                {
                    INVOICE_INFO info = new INVOICE_INFO();
                    info.AMOUNT = amount.Value;
                    info.AGENT_NO = u.AgentNo;
                    info.INCOICE_TIME = DateTime.Now;
                    info.INVOICE_NO = form["INVOICE_NO" + i.ToString()].ToText();
                    info.INVOICE_TYPE = form["INVOICE_TYPE" + i.ToString()].ToInt().Value;
                    info.OPERATOR_NO = u.OPERATOR_NO;
                    info.REMARK = form["REMARK" + i.ToString()].ToText();
                    info.STATUS = 1;
                    info.USER_NO = log.USER_NO;

                    list.Add(info);
                }
            }

            return list;
        }

        [HttpPost]
        public ActionResult Search(string RepairOrderNO)
        {
            //交流流水信息

            //IEnumerable<PRINT_LOGINVOICE> transactions = null;
            //if (RepairOrderNO != "")
            //    RepairOrderNO = " AND SERIAL_NO='" + RepairOrderNO + "'";
            ////var allItems = db.PRINT_LOG;
            //var allItems = GetInvoice(RepairOrderNO);
            //transactions = allItems;
            //var model = (from t in transactions
            //             select toTransactionLogViewModel(t)).ToList();


            //var temp = new GridModel(model);
            //return View(temp);

            try
            {
                string sql = "";
                if (RepairOrderNO != "")
                    sql = " AND SERIAL_NO='" + RepairOrderNO + "'";
                return Json(new { Sql = sql, Success = true, ErrorMsg = "" });
            }
            catch (Exception ex)
            {
                return Json(new { Sql = "", Success = false, ErrorMsg = ex.Message });
            }

        }

        [HttpPost]
        public ActionResult checkInvoiceExisit(string strIDs)
        {
            try
            {
                string[] serialIDArray = strIDs.Split(',');

                var longIDs = from id in serialIDArray
                              select id.ToLong().Value;

                var result = from d in db.INVOICE_INFO
                             where (from i in db.INVOICE_DETAIL
                                    where longIDs.Contains(i.SERIAL_ID)
                                    select i.INVOICE_ID).Contains(d.ID) && d.STATUS == 1
                             select d;

                if (result != null && result.ToList().Count() > 0)
                    return Json(new { Sql = result, Success = false, ErrorMsg = "该流水单已开具发票" });
                else
                    return Json(new { Sql = result, Success = true, ErrorMsg = "" });
            }
            catch (Exception ex)
            {
                return Json(new { Sql = "", Success = false, ErrorMsg = ex.Message });
            }
        }
        public ActionResult checkIsExistinfo(string serialNo)
        {
            var serialInfo = (from i in db.PRINT_LOG.ToList()
                              where i.SERIAL_NO == serialNo
                              select i).FirstOrDefault();

            return checkInvoiceExisit(serialInfo.ID.ToString());
        }

    }
}
